package com.aceitunaproject.gameclient;

import java.awt.Point;
import java.util.List;

import com.aceitunaproject.mapdisplay.component.MapPane;
import com.aceitunaproject.mapdisplay.model.Thing;
import com.aceitunaproject.mapdisplay.model.map.Position;
import com.aceitunaproject.mapdisplay.model.map.tile.Tile;
import com.aceitunaproject.shared.gamelement.Installation;
import com.aceitunaproject.shared.gamelement.Settlement;
import com.aceitunaproject.shared.map.MapTile;

/**
 * 
 * Map pane extension, contains the logic that transforms the Shared Map Tiles
 * to a MapDisplay map.
 * 
 * @author Federico Bergstein
 * 
 */
public class MapArea extends MapPane {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private AceitunaView view;
	
	public MapArea(List<MapTile> tiles,AceitunaView view) {
		super(translateTiles(tiles));
		this.view = view;
		this.addMouseListener(new MapMouseListener(this));
		
	}

	public void setMapModel(List<MapTile> tiles) {
		setMapModel(translateTiles(tiles));
	}

	private static Tile[][] translateTiles(List<MapTile> tiles) {

		int n = 0;

		Tile[][] resultTiles = new Tile[7][15];
		for (int i = 0; i < resultTiles.length; i++) {
			for (int j = 0; j < resultTiles[i].length; j++) {
				resultTiles[i][j] = createTile(i, j, "");

				n++;
			}
		}

		for (MapTile mapTile : tiles) {

			resultTiles[mapTile.getPosx()][mapTile.getPosy()]
					.setBasicTileType(mapTile.getTerrain().get(0).getName());

			Settlement theSettlement = mapTile.getSettlement();
			if (theSettlement != null) {
				System.out.println("settlement!");
				Thing t = new Thing("Settlement");
				resultTiles[mapTile.getPosx()][mapTile.getPosy()].addThing(t);
			}

			for (Installation installation : mapTile.getInstallations()) {
				System.out.println("Installation!");
				String instType = "";
				if (installation.isComplete()) {
					instType = "installation_" + installation.getType();
				} else {
					instType = "installation_Incomplete";
				}
				Thing t = new Thing(instType);
				resultTiles[mapTile.getPosx()][mapTile.getPosy()].addThing(t);
			}

			for (int i = 0; i < mapTile.getUnits().size(); i++) {

				Thing t = new Thing("unit");
				resultTiles[mapTile.getPosx()][mapTile.getPosy()].addThing(t);
			}

		}

		return resultTiles;
	}

	private static Tile createTile(int x, int y, String name) {

		return new Tile(name, x, y);

	}

	public void mapClicked(EnumMouseButton button, Point point) {
	
		view.mapClicked(button,translateToPoint(mapDrawer.convertToMapCoordinates(point.x, point.y)));
		getGraphics().fillOval(point.x, point.y, 2, 2);
	}

	private Point translateToPoint(Position p) {

		return new Point(p.getX(),p.getY());
	}
	
	
}
